package com.tensuqare.user.service;

import com.tensuqare.user.dao.AdminDao;
import com.tensuqare.user.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import util.IdWorker;

@Service
public class AdminService {

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private IdWorker idWorker;

    //新增管理员
    public void addAdmin(Admin admin) {

        //使用idworker进行自动生成用户名
        admin.setId(idWorker.nextId()+"");
        //使用bcry进行加密
        admin.setPassword(bCryptPasswordEncoder.encode(admin.getPassword()));
        //新增
        System.out.println("admin = " + admin);
        adminDao.save(admin);
    }
    //管理员登录
    public Admin login(Admin admin) {
        //根据用户名获取这个用户的信息
        Admin byLoginname = adminDao.findByLoginname(admin.getLoginname());
        System.out.println("byLoginname = " + byLoginname);
        //使用bcry的matches进行解密（从前端获取输入的密码，注册加密过的密码）
        if(byLoginname!=null&&bCryptPasswordEncoder.matches(admin.getPassword(),byLoginname.getPassword())){
            return byLoginname;
        }
        return null;
    }

    //根据ID删除
    public void deleteAdmin(String adminId) {
        adminDao.deleteById(adminId);
    }
}
